import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 导入数据
data = pd.read_excel('第二章 图表(后15).xlsx',sheet_name='23 柱形折线图',usecols='B:D',skiprows=1)
print(data)

# 数据准备
x = data['年份'].tolist()
y = data['销售量'].tolist()
z = (data['同比']).tolist()

# 创建图形和坐标轴
fig, ax = plt.subplots(figsize=(8, 6))

# 设置背景颜色
fig.patch.set_facecolor('#00002d')
ax.set_facecolor('#00002d')

# 隐藏边框
for spine in ax.spines.values():
    spine.set_visible(False)

# 设置X轴标签
ax.set_xticks(x)
ax.set_xticklabels(data['年份'], color='w')
# 设置Y轴标签颜色为白色
ax.set_yticks([])
ax.set_ylim(0, 7000)
ax.set_yticklabels(ax.get_yticks(), color='w')
# 绘制柱形图
bars = ax.bar(x,y, color='dodgerblue', width=0.3, label='销售量')
# 输出每个柱子的值
for i in range(len(x)):
    ax.text(x[i], y[i], f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10)

# 创建第二个坐标轴
ax2 = ax.twinx()
# 设置范围
ax2.set_ylim(min(z) * (-10), max(z) * 1.2)
# 绘制折线图
ax2.plot(x, z,'o-', color='tomato', linewidth=2, markeredgecolor='#00002d', label='同比')
# 输出每个点的值
for i in range(len(x)):
    ax2.text(x[i], z[i] + 0.02, f'{int(z[i] * 100)}%', ha='center', color='w', fontsize=10)

# 调整图形位置
plt.subplots_adjust(top=0.8)  # 留出空间给标题

# 添加标题
plt.text(0, 1.15, '近六年销售量及增长率', color='w', fontsize=24, transform=ax.transAxes)
plt.text(0, 1.05, '平台销量近6年持续增长，但近两年增长率有所放缓', color='w', fontsize=16, transform=ax.transAxes)

# 添加图例
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='best', facecolor='#00002d', labelcolor='w')

# 导出图片
#plt.savefig('D:/python charm/01/可视化/第二章/图片/柱形折线图.png', dpi=300, bbox_inches='tight', facecolor='#00002d')
plt.show()